<template>
    <rx-dialog @ok="handleSubmit" @cancel="cancel" :okText="$ti18('rxForm.saveBtn','保存')">
        <rx-layout>
            <template #middle>
                <div style=" height: 100%; padding: 20px;">
                    <a-tabs default-active-key="1">
                        <a-tab-pane key="1" :tab="i18n('shareConfig','分享配置')">
                            <div style="margin:10px;">
                                <div>
                                    <a-radio-group v-model:value="screenPermission.type">
                                        <a-radio value="none">{{i18n("none","仅个人")}}</a-radio>
                                        <a-radio value="everyone">{{i18n("everyone","所有人")}}</a-radio>
                                        <a-radio value="custom">{{i18n("custom","自定义")}}</a-radio>
                                    </a-radio-group>
                                </div>
                                <a-alert style="margin-top:10px" v-if="screenPermission.type =='custom'" :message="i18n('alert','如果勾选了不包含，是除开选中的都有权限，不勾选则选中的有权限')" type="info" show-icon />
                                <template v-if="screenPermission.type=='custom'">
                                    <ul style="margin-top:10px">
                                        <li style="margin-top:10px" v-for="(setting, index) in customSettings" :key="index">
                                            <form-user-or-group :tips="true" ref="userOrGroup" :value="setting"></form-user-or-group>
                                        </li>
                                    </ul>
                                </template>
                            </div>
                        </a-tab-pane>
                        <a-tab-pane key="2" :tab="i18n('publicLinkConfig','公共链接配置')" force-render>
                            <div style="margin:10px;">
                                <a-form :model="screenLinkShare" >
                                    <a-form-item :label="i18n('linkShare','链接分享')">
                                        <a-switch  size="small" v-model:checked="screenLinkShare.link"/>
                                        <div style="color: grey;line-height: 20px">{{i18n('openTips','开启后,任意内部成员登录系统后都能访问仪表板')}}</div>
                                    </a-form-item>
                                    <div style="margin-top: 10px" v-if="screenLinkShare.link">
                                        <a-form-item  :label="i18n('link','链接')">
                                            <div style="display: flex;">
                                                <a-input style="flex: 1;margin-right: 10px" v-model:value="url" :disabled="true">
                                                    <template #suffix>
                                                        <rx-icon-show icon="iconsend" :title="i18n('openWindow','新窗口打开')" @click="openNew"></rx-icon-show>
                                                    </template>
                                                </a-input>
                                                <a-button type="primary" @click="copyUrl(url)">{{i18n('replicationConnection','复制连接')}}</a-button>
                                            </div>
                                        </a-form-item>
                                        <a-form-item :label="i18n('expirationDate','有效期')">
                                            <a-date-picker allowClear style="width: calc(100% - 100px)" v-model:value="expirationDate"  show-time :format="format"  :locale="locale"/>
                                        </a-form-item>
                                        <a-form-item :label="i18n('isPassword','密码保护')">
                                            <a-switch size="small" v-model:checked="screenLinkShare.isPassword" @change="setPassword"/>
                                            <div v-if="screenLinkShare.isPassword" style="display: flex;">
                                                <a-input style="flex: 1;margin-right: 10px"  v-model:value="screenLinkShare.password"/>
                                                <a-button type="primary" @click="copyUrl(screenLinkShare.password)">{{i18n('copyPassword','复制密码')}}</a-button>
                                            </div>
                                        </a-form-item>
                                    </div>
                                </a-form>
                            </div>
                        </a-tab-pane>
                    </a-tabs>
                </div>
            </template>
        </rx-layout>
    </rx-dialog>
</template>

<script>
import ScreenApi from "@/api/screen-api";
import FormUserOrGroup from "./form-user-or-group.vue";
import {RxDialog, RxLayout, Util} from "@lowcode/jpaas-base-lib"
import { App } from '@lowcode/jpaas-share-component';
import ScreenViewManageApi from '@/api/screen/core/screen-view-manage.js';
import dayjs from "dayjs";
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';

export default {
    name: "ScreenShare",
    props: ["alias","destroy"],
    mixins: [App],
    components: {
        RxDialog,
        RxLayout,
        FormUserOrGroup
    },
    data() {
        return {
            url: "",
            serverAddress: "",
            curUser: "",
            //权限配置
            screenPermission: {
                type: "none",
                customSettings: []
            },
            //初始化自定义配置
            customSettings: [
                {name: this.i18n('subGroup', '组织或以下'), type: "subGroup", names: "", values: "", include: true},
                {name: this.i18n('user', '用户'), type: "user", names: "", values: "", include: true},
                {name: this.i18n('group', '用户组'), type: "group", names: "", values: "", include: true},
            ],
            expirationDate: "",
            format: "YYYY-MM-DD HH:mm",
            screenLinkShare: {
                pkId: "",
                link: false,
                url: "",
                expirationDate: "",
                isPassword: false,
                password: "",
            },
            labelCol: {span: 4},
            wrapperCol: {span: 18},
            locale
        }
    },
    created() {
        this.getServerAddress();
        this.initPermissionAndShare();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "screenShareLang", key);
        },
        designI18n(name, text, key) {
            return this.$ti18(name, text, "designLang", key);
        },
        getServerAddress() {
            ScreenApi.getServerAddress().then(res => {
                if (res) {
                    this.serverAddress = res.serverAddress;
                    this.curUser = res.currentUser;
                    this.init();
                }
            });
        },
        init() {
            let url = "/screen/share/";
            let paramStr = this.encryParam();
            this.url = this.serverAddress + url + paramStr;
        },
        //初始化加载权限与分享配置
        initPermissionAndShare() {
            ScreenViewManageApi.getPermissionAndShare(this.alias).then(res => {
                if (res && res.data) {
                    //权限
                    let screenPermissions = res.data.screenPermissions;
                    if (screenPermissions && screenPermissions.length > 0) {
                        this.screenPermission.type = screenPermissions[0].type;
                        if (screenPermissions[0].type == 'custom') {
                            for (let i = 0; i < screenPermissions.length; i++) {
                                let permission = screenPermissions[i];
                                for (let j = 0; j < this.customSettings.length; j++) {
                                    if (this.customSettings[j].type == permission.userOrGroupType) {
                                        if (this.customSettings[j].names) {
                                            this.customSettings[j].names += ",";
                                        }
                                        this.customSettings[j].names += permission.userOrGroupName;
                                        if (this.customSettings[j].values) {
                                            this.customSettings[j].values += ",";
                                        }
                                        this.customSettings[j].values += permission.userOrGroupId;
                                        this.customSettings[j].include = permission.include === 1;
                                    }
                                }
                            }
                        }
                    }
                    //公共链接分享
                    if (res.data.screenLinkShare) {
                        let screenLinkShare = res.data.screenLinkShare;
                        this.screenLinkShare = {
                            pkId: screenLinkShare.pkId,
                            link: screenLinkShare.status === 1,
                            url: screenLinkShare.url,
                            expirationDate: screenLinkShare.expirationDate,
                            isPassword: screenLinkShare.isPassword === 1,
                            password: screenLinkShare.password
                        };
                        this.expirationDate = screenLinkShare.expirationDate ? dayjs(screenLinkShare.expirationDate) : "";
                    }
                }
            });
        },
        /**
         * 加密参数
         * @returns {string}
         */
        encryParam() {
            let paramStr = "";
            let params = {
                alias: this.alias,
                appId: this.curApp.appId,
                userId: this.curUser.userId
            }
            paramStr = window.encodeURIComponent(JSON.stringify(params));
            return window.btoa(paramStr); // 编码
        },
        copyUrl(url) {
            if (!this.screenLinkShare.pkId) {
                this.$message.warning(this.i18n('saveTips', '当前配置未保存！'));
                return;
            }
            let tag = document.createElement('input');
            tag.setAttribute('id', 'copyInput');
            tag.value = url;
            document.getElementsByTagName('body')[0].appendChild(tag);
            document.getElementById('copyInput').select();
            document.execCommand('copy');
            document.getElementById('copyInput').remove();
            this.$message.success(this.designI18n("msa.copyTips", "复制成功!"));
        },
        openNew() {
            if (!this.screenLinkShare.pkId) {
                this.$message.warning(this.i18n('saveTips', '当前配置未保存！'));
                return;
            }
            window.open(this.url);
        },
        getData() {
            if (this.screenPermission.type == "custom") {
                this.screenPermission.customSettings = this.customSettings;
            }
            if(this.expirationDate){
                this.screenLinkShare.expirationDate=dayjs(this.expirationDate,this.format);
            }else {
                this.screenLinkShare.expirationDate="";
            }
            return {
                alias: this.alias,
                screenPermission: this.screenPermission,
                screenLinkShare: this.screenLinkShare
            }
        },
        handleSubmit(vm) {
            ScreenViewManageApi.savePermissionAndShare(this.getData()).then(() => {
                this.initPermissionAndShare();
                vm.loading = false;
            });
        },
        cancel() {
            Util.closeWindow(this, "cancel");
        },
        setPassword(value) {
            if (value) {
                this.screenLinkShare.password = Util.randomId();
            } else {
                this.screenLinkShare.password = "";
            }
        }
    },
    watch: {}
}
</script>

<style scoped>

</style>
